package com.weilele.mvvm.widget

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.bumptech.glide.Glide
import com.google.android.material.imageview.ShapeableImageView
import com.weilele.mvvm.utils.activity.getActivity
import com.weilele.mvvm.utils.glide.OkHttpLoadImage
import com.weilele.mvvm.utils.glide.setImageGlide

/**
 * 描述：
 * imageView?.shapeAppearanceModel = ShapeAppearanceModel.builder()
 * .setAllCorners(CornerFamily.ROUNDED,20f)
 * .setTopLeftCorner(CornerFamily.CUT,RelativeCornerSize(0.3f))
 * .setTopRightCorner(CornerFamily.CUT,RelativeCornerSize(0.3f))
 * .setBottomRightCorner(CornerFamily.CUT,RelativeCornerSize(0.3f))
 * .setBottomLeftCorner(CornerFamily.CUT,RelativeCornerSize(0.3f))
 * .setAllCornerSizes(ShapeAppearanceModel.PILL)
 * .setTopLeftCornerSize(20f)
 * .setTopRightCornerSize(RelativeCornerSize(0.5f))
 * .setBottomLeftCornerSize(10f)
 * .setBottomRightCornerSize(AbsoluteCornerSize(30f))
 * .build()
 */
open class BaseImageView : AppCompatImageView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    open fun setImageUrl(url: String?) {
        if (url.isNullOrBlank()) {
            setImageDrawable(null)
        } else {
            setImageGlide(url)
        }
    }

    private var onProgressListener: OkHttpLoadImage.OnProgressListener? = null

    open fun setImageUrl(url: String?, listener: (Float/*进度从0-1f*/) -> Unit) {
        if (url.isNullOrBlank()) {
            setImageDrawable(null)
        } else {
            OkHttpLoadImage.unRegister(onProgressListener)
            onProgressListener = object : OkHttpLoadImage.OnProgressListener {
                override fun getKey(): String {
                    return url
                }

                override fun onProgress(progress: Float) {
                    post {
                        listener.invoke(progress)
                        if (progress >= 1f) {
                            OkHttpLoadImage.unRegister(onProgressListener)
                            onProgressListener = null
                        }
                    }
                }
            }
            OkHttpLoadImage.register(onProgressListener)
            setImageUrl(url)
        }
    }

    override fun onDetachedFromWindow() {
        OkHttpLoadImage.unRegister(onProgressListener)
        onProgressListener = null
        super.onDetachedFromWindow()
    }
}